import { router } from '@/router'
import { useUserStore } from '@/store'
import Axios from 'axios'
import { ElMessage } from 'element-plus'

const instance = Axios.create({
    baseURL : 'http://xue.cnkdl.cn:9082/mall-admin/',
    timeout: 5000
})

instance.interceptors.request.use(config=>{
    let token = localStorage.getItem('token')
    if(token) {
        config.headers && (config.headers['Authorization'] = token)
    }
    return config;
},err=>Promise.reject(err))

instance.interceptors.response.use(res=>{
    const userStore = useUserStore()
    if(res.data.code === 401) {
        localStorage.removeItem('token')
        router.push("/login")
        userStore.activemenus.forEach(item => {
            router.removeRoute(item.name)
        });
        router.removeRoute("home")
        userStore.menus = []
        userStore.username = ""
    }

    res.data.code !== 200 && ElMessage.error(res.data.message);
    
    return res.data;
},
err=>{
    ElMessage.error("请求出问题了，请联系管理员")
    return Promise.reject(err)
});


export default instance;